<?php
define('WEBPATH', realpath( __DIR__."/../"));
require_once WEBPATH."/lib_config.php";

$serv = new swoole_server('0.0.0.0', 9514);
$serv->set(array(
    'daemonize' => 1,
    'worker_num' => 50, //worker进程数量
//    'task_worker_num' => 10, //task进程数量 即为维持的MySQL连接的数量
    'log_file' => '/var/www/swoole/cli/log/9514.log',
    'max_request' => 10000, // 单个worker 最大处理数
    "open_eof_check" => 1,
    "package_eof" => "\r\n\r\n",
    "dispatch_mode" => 1  // 1平均分配 2固定taskid 3 抢占
));


function my_onWorkerStart($serv, $worker_id)
{

    $ip = '120.31.131.231'; // redis服务器ip地址
    $port = '6379'; // redis服务器端口
    $passwd = '!@#$981596276'; // redis密码
    $redis = new Swoole\Coroutine\Redis();
    $redis->connect($ip, $port);
    $redis->auth($passwd);
    $keys = "list-data";
    $secondList = "second-data";


    $config['type'] = \Swoole\Database::TYPE_MYSQLi;
    $config['host'] = '120.31.136.107';
    $config['user'] ='root';
    $config['password'] = 'd23a048282d9f0e3';
    $config['database'] = 'pay_system_v5';

    $db = new Swoole\Database($config);
    $db->connect();


    for ($i=0;$i<999999999999999;$i++){
        $data = $redis->brPop($keys, 2);
        if ($data == false) {
            continue;
        }
        file_put_contents("/var/www/swoole/cli/log/redis2.txt",json_encode($data)."--|\r\n",FILE_APPEND);
        $data = json_decode($data[1], true);
        if($data) {
            $result = $db->query("SELECT * FROM pay_order where order_id =  '{$data['order_id']}'",5);
            $result = $result->fetch();

            PostNotify($db,$data['order_id'],$result, $data['bank_money'],$data['notify_type']);
//            $temp = request_post($result['notify_url'], json_encode($result));
//            if ($temp == "SUCCESS" || $temp == "success") {
//                $rand = mt_rand(1000, 99999);
//                $db->query("update pay_order set  platform = '{$rand}' where order_id = '{$data['order_id']}'");
//            }

        }
    }

}


function my_onReceive($serv, $fd, $from_id, $data)
{
}

function my_onTask($serv, $task_id, $from_id, $sql)
{

}

function my_onFinish($serv, $task_id, $data)
{
}

//消息通知  写入日志
function PostNotify($mysql,$orderid,$orderinfo, $bank_money = 0,$notify_type = 1)
{

    $notify_log = "/var/www/swoole/cli/log/" . 'nodesyn-' . date('Y-m-d', time()) . '.txt';
    $notify_log2 = "/var/www/swoole/cli/log/" . 'syn_olddata-' . date('Y-m-d', time()) . '.txt';

    $notify_data = '';
    $notify_data .= date('Y-m-d H:i:s', time());
    $notify_data .= '|' . $orderid;
    if ($orderinfo && $bank_money) {
        $url = $orderinfo["notify_url"];
        if (!empty($orderinfo["sn"])) {
            $transactionId = $orderinfo["sn"];
        } else {
            $transactionId = $orderinfo["up_sn"];
        }
        $data = array(
            'order_id' => $orderinfo["order_id"],
            'orderNo' => $orderinfo["system_order_id"],
            'money' => $bank_money,
            'mch' => $orderinfo["mch"],
            'pay_type' => $orderinfo["pay_type"],
            'commodity_name' => $orderinfo["commodity_name"],
            'extra' => $orderinfo["extra"],
            'transactionId' => $transactionId,
            'time' => $orderinfo["down_time"],
            'status' => 1,
            'sign' => md5($orderinfo["order_id"] . $orderinfo["system_order_id"] . $bank_money . $orderinfo["mch"] . $orderinfo["pay_type"] . $orderinfo["down_time"] . md5($orderinfo["mch_key"])),
        );

        $sign_str = $orderinfo["order_id"] . '--' . $orderinfo["system_order_id"] . '--' . $bank_money . $orderinfo["mch"] . '--' . $orderinfo["pay_type"] . '--' . $orderinfo["down_time"] . '--' . $orderinfo["mch_key"];
        file_put_contents($notify_log2, $sign_str . PHP_EOL, FILE_APPEND);
        $url = str_replace('&amp;', '&', $url);
        $notify_data .= '|' . json_encode($data) . '|' . $url;
        if ($notify_type == 2) {
            $newdata = @http_build_query($data);  //把参数转换成URL数据
            $get_url = $url . '?' . $newdata;
            $result = @file_get_contents($get_url);
            $notify_data .= '|get同步结果' . json_encode($result);
        }
        if($notify_type == 1){
            $result = request_post($url, $data);
            $notify_data .= '|同步结果' . json_encode($result);
        }
        $result = strtolower($result);
        $pos = strpos($result, 'success');
        if ($pos === false) {
            $return_res = 'ERR2';
        } else {
            $return_res = "OK";
            $time = time();
            //更改下单时间 和 返回成功更改订单状态
            $mysql->query("update pay_order set  down_time = '{$time}' , notify_status = 1 where order_id = '{$orderid}'");

        }
        $notify_data .= '|res=' . $return_res;
        file_put_contents($notify_log, $notify_data . PHP_EOL, FILE_APPEND);

    } else {
        $return_res = "orderinfo is null";
        $notify_data .= '|res=' . $return_res;
        file_put_contents($notify_log, $notify_data . PHP_EOL, FILE_APPEND);
    }

}

function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($ch, CURLOPT_TIMEOUT,35);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

function send_post($postUrl, $post_data = '', $isxml = false, $timeout = 8)
{
    if (empty($postUrl) || empty($post_data)) {
        return false;
    }
    $curlPost = $post_data;
    $header[] = "Content-type: text/html";
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

$serv->on('receive', 'my_onReceive');
$serv->on('task', 'my_onTask');
$serv->on('Finish', 'my_onFinish');
$serv->on('WorkerStart', 'my_onWorkerStart');

$serv->start();//启动server
